﻿using System;
using System.Runtime.Caching;
using System.Threading.Tasks;
using QD.Snapshot.Core.Config;
using QD.Utill;

namespace QD.Snapshot.Core.Util
{
    public class MsgHelper
    {
        static HttpRequest request = new HttpRequest();
        /// <summary>
        /// 发送验证码通知
        /// </summary>
        /// <param name="msg">通知内容</param>
        /// <param name="engineType">引擎</param>
        public static void SendCodeMessage(string msg, EngineType engineType)
        {
            var key = engineType.ToString();
            if (MsgTimerHelper.IsSend(key)) return;
            if (string.IsNullOrEmpty(SiteConfig.NotifyToUser)) return;

            Task.Factory.StartNew(() =>
            {
                SendMessage(msg, SiteConfig.NotifyToUser);
                MsgTimerHelper.Set(key, DateTime.Now);  //记录发送状态
            });
        }

        public static void SendMessage(string msg, string toUser)
        {
            var url = string.Format("http://weapp.711688.net.cn/api/tool/sendtextmessage?storeid=4&msg={0}&touser={1}", msg, toUser);
            var html = request.Requset(url);
        }
    }

    internal class MsgTimerHelper
    {
        static MemoryCache memoryCache = new MemoryCache("msg_time");

        public static void Set(string key, object value, int minutes = 30)
        {
            var timer = new DateTimeOffset(DateTime.Now.AddMinutes(minutes));
            memoryCache.Set(key, value, timer);
        }

        /// <summary>
        /// 是否发送过
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static bool IsSend(string key)
        {
            if (memoryCache.Contains(key))
            {
                return true;   //未过期
            }
            return false;
        }
    }
}
